package Tools;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Date;
import java.util.TimerTask;


public class obtainStats extends TimerTask{
	Stats parent;
	long timeNow;
	Histogram oldHistogram;

	public obtainStats(Stats parent){
		this.parent=parent;

	}

	public void run(){
		timeNow=new Date().getTime();

		this.oldHistogram = parent.getActiveHistogram();
		parent.clearActiveHistogram();
		outputStats();
	}

	private void outputStats(){
		System.out.println("Number of Requests: "+oldHistogram.numEntries);
		System.out.println("Hist "+oldHistogram.hist[0]+" "+oldHistogram.hist[1]+" "+oldHistogram.hist[2]+" "+oldHistogram.hist[3]+" "+oldHistogram.hist[4]+" "+oldHistogram.hist[5]+" "+oldHistogram.hist[6]+" "+oldHistogram.hist[7]);
		this.openURL("http://10.1.1.4:9111/vcontrol/metric/collect?app=tpcw&vm=cmubisapp3&host=10.1.1.4&response_average="+oldHistogram.getPercentile(0.5)+"&time="+(timeNow-parent.refreshPeriod)+"&endtime="+timeNow);
	}

	private void openURL(String urlString){
		try{
			URL url = new URL(urlString);
			BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));

			String pageLine;
			while ( (pageLine = br.readLine()) != null ) {
			}

			br.close();
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
}
